import { RangePickerProps } from 'ant-design-vue/es/date-picker/interface'

import moment from 'moment'
import 'moment/locale/zh-cn'

moment.locale('zh-cn')

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {

    const date = []
    if (this.value && this.value.length > 0) {
      if (typeof this.value[0] === 'string') {
        date[0] = moment(this.value[0], this.format || 'YYYY-MM-DD HH:mm:ss')
      } else {
        date[0] = moment(this.value[0])
      }
      if (this.value.length > 1) {
        if (typeof this.value[0] === 'string') {
          date[1] = moment(this.value[1], this.format || 'YYYY-MM-DD HH:mm:ss')
        } else {
          date[1] = moment(this.value[1])
        }

      }
    }
    return {
      date: date
    }
  },
  props: Object.assign({}, RangePickerProps(), {
    value: {
      type: Array
    }
  }),
  watch: {
    value: {
      handler: function(val = []) {
        if (val && val.length > 0) {

          if (typeof this.value[0] === 'string') {
            this.date[0] = moment(val[0], this.format || 'YYYY-MM-DD HH:mm:ss')
          } else {
            this.date[0] = moment(val[0])
          }
          if (this.value.length > 1) {
            if (typeof this.value[0] === 'string') {
              this.date[1] = moment(val[1], this.format || 'YYYY-MM-DD HH:mm:ss')
            } else {
              this.date[1] = moment(val[1])
            }

          }
        }else {
          this.date=[]
        }
      },
      immediate: true
    }
  },
  created() {

  },
  methods: {
    change(date, dateString) {
      let res = []
      if (date) {
        if (date.length > 0) {
          res[0] = date[0].toDate()
          if (date.length > 1) {
            res[1] = date[1].toDate()
          }
        }
      }
      this.$emit('change', res)
    }
  },

  render() {
    const props = {}

    Object.keys(RangePickerProps()).forEach(key => {
      if (this[key]) {
        props[key] = this[key]
      }
    })
    delete props.value
    return (
      <a-range-picker {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.change} value={this.date}>
        {Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>))}
      </a-range-picker>
    )
  }
}
